package com.manage.utils;

import org.hibernate.service.spi.ServiceException;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 关于异常的工具类.
 * @author jax
 */
public class ExceptionsUtil {

	private final static String EXCEPTION_NAME="exception";

	private final static String EXCEPTION_NAME_SPASE="javax.servlet.error.exception";

	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getStackTraceAsString(Throwable e) {
		if (e == null){
			return "";
		}
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * 判断异常是否由某些底层的异常引起.
	 */
	@SafeVarargs
	public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex.getCause();
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}

	/**
	 * 在request中获取异常类
	 * @param request
	 * @return 
	 */
	public static Throwable getThrowable(HttpServletRequest request){
		Throwable ex = null;
		if (request.getAttribute(EXCEPTION_NAME) != null) {
			ex = (Throwable) request.getAttribute(EXCEPTION_NAME);
		} else if (request.getAttribute(EXCEPTION_NAME_SPASE) != null) {
			ex = (Throwable) request.getAttribute(EXCEPTION_NAME_SPASE);
		}
		return ex;
	}

	/***
	 * 获取系统抛出的异常
	 * @param ex
	 * @return
	 */
	public static void getThrowableString(Throwable ex,StringBuffer str){
		if(null!=ex.getCause()|| StrUtil.isBlank(str)){
			if(ex.getCause() instanceof ServiceException){
				str.append(ex.getCause().getMessage());
			}else {
				getThrowableString(ex.getCause(),str);
			}
		}
	}
}
